<?php
/**
 * 请求接口中间件（写入日志）
 */
namespace App\Http\Middleware;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use DB,File;

class ApiLogOperation
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        if ($this->shouldLogOperation($request)) {
            // 创建文件夹
            $directory = date('Y').'-'.date('m').'-'.date('d');
            if (!Storage::disk('local')->exists($directory)) {
                Storage::disk('local')->makeDirectory($directory);
            }
//            dd($request->path());
            $num = 1;
            //2个文件   num = 2；   1 num = 1  再判断最后一个文件大小 如果大于5M
            $user = Auth::guard('api')->user();
            $log_array = [
                'user_id' => isset($user) ? Auth::guard('api')->user()->id : 0,
                'path'    => $request->path(),
                'method'  => $request->method(),
                'ip'      => $request->getClientIp(),
                'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Unknown', // 服务器头信息
                'input'   => json_encode($request->input()),
                'header'    => json_encode($request->header()),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            //$log = "[".Carbon::now()."]".json_encode($log_array);

//            $file_name = $directory.'/'.$num.'.txt';

            // 获取文件夹下的所有文件
            if (Storage::disk('local')->allFiles($directory)) {
                $allfiles = Storage::disk('local')->files($directory);
                $newArr = [];
                foreach ($allfiles as $key=>$val) {
                    $arr = explode('/',$val);
                    $newArr[$key] = array_pop($arr);
                }
                $files = array_sort($newArr);
                // 获取最后一个文件
                $last_file = array_pop($files);
            }else{
                $last_file = $num.'.log';
            }

            $file_name = $directory.'/'.$last_file;

            if (Storage::disk('local')->exists($file_name)) {
                $size = Storage::disk('local')->size($file_name);
                $log_array['file_name'] = $file_name;
                $log_array['size'] = $size;

                // 判断文件大小
                if ($size > intval(config('cdyz.fileSize'))) {
                    $name = explode('.',$last_file);
                    $num = $name[0] + 1;
                    $file_name = $directory.'/'.$num.'.log';
                }else{
                    $file_name = $directory.'/'.$last_file;
                }
            }else{
                $file_name = $directory.'/'.$last_file;
            }
            $log = "[".Carbon::now()."]".json_encode($log_array);
            // 储存文件  添加内容到文件结尾
            //Storage::disk('local')->append($file_name,$log);
            file_put_contents(storage_path('app/'.$file_name),$log . PHP_EOL, FILE_APPEND);
        }

        return $next($request);
    }

    /**
     * @param Request $request
     *
     * @return bool
     */
    protected function shouldLogOperation(Request $request)
    {
        return true;
             //&& !$this->inExceptArray($request)
             //&& Auth::guard('api')->user();
    }

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function inExceptArray($request)
    {

        foreach (['api/other/operate_log*'] as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            $methods = [];

            if (Str::contains($except, ':')) {
                list($methods, $except) = explode(':', $except);
                $methods = explode(',', $methods);
            }

            $methods = array_map('strtoupper', $methods);

            if ($request->is($except) &&
                (empty($methods) || in_array($request->method(), $methods))) {
                return true;
            }
        }

        return false;
    }
}
